Qt.include("OAuth.js");
// This is not in the repository. Request own app consumer key and secret if you wish to compile
Qt.include("FutuHeiaKeys.js");


var sportsPage = 1;
var TOTAL_SPORTS_PAGE_COUNT = 18; // ~348 sports currently (23.11.2010) in total
var sportsXML = "";

function log(message) {
    console.log("[HEIA] " + message);
}

function getCoordinateXForView(viewNumber) {
    var x = screenWidth * viewNumber;
    log("getCoordinateXForView(" + viewNumber + "), return x: " + x);
    return x;
}

// API stuff
var API_URL_GET_SPORTS = "http://www.heiaheia.com/api/v1/sports";
var API_URL_POST_ENTRY = "http://www.heiaheia.com/api/v1/training_logs";

var REQUEST_TYPE_GET_SPORTS = 1;
var REQUEST_TYPE_POST_ENTRY = 2;

function log(message) {
    console.log("[HEIA] " + message);
}

function getSports(pageNumber) {
    log("getSports, page " + pageNumber);
    var params = new Array();
    params.push(["page", pageNumber]);
    var req = getAPIOAuthRequest("GET", API_URL_GET_SPORTS, null, [appItem.accessToken, appItem.accessTokenSecret], params, null, REQUEST_TYPE_GET_SPORTS);
    req.send();
}

function canPost() {
    log("date = " + appItem.date);
    log("month = " + appItem.month);
    log("year = " + appItem.year);
    log("durationHours = " + appItem.durationHours);
    log("durationMinutes = " + appItem.durationMinutes);
    log("distance = " + appItem.distance);
    log("mood = " + appItem.mood);
    log("comment = " + appItem.comment);
    log("selectedName = " + appItem.selectedName);
    log("selectedId = " + appItem.selectedId);

    var sportId = appItem.selectedId;
    var hours = appItem.durationHours;
    var minutes = appItem.durationMinutes;
    var distance = appItem.distance;

    if (hours === 0 && minutes === 0) {
        log("Cannot post. No duration");
        return false;
    }
    if (sportId === 0) {
        return false;
    }

    return true;
}

function showLog() {
    log("showLog");
    if (appItem.state === "showingLog") {
        appItem.postsButtonText = qsTr("Show posts");
        appItem.state = "showingMain";
    } else {
        appItem.postsButtonText = qsTr("Hide posts");
        appItem.state = "showingLog"
    }
}

function postEntry() {
    log("postEntry");

    var sportId = appItem.selectedId;
    var date = appItem.year + "-" + appItem.month + "-" + appItem.date;
    var hours = appItem.durationHours.trim();
    var minutes = appItem.durationMinutes.trim();
    var distance = appItem.distance.trim();
    var comment = appItem.comment.trim();
    var mood = appItem.mood

    var parameters = new Array();

    parameters.push( ["sport_id", sportId] );
    parameters.push( ["training_log[date]", date] );
    if (hours.length > 0)
        parameters.push( ["training_log[duration_h]", hours] );
    if (hours.minutes > 0)
        parameters.push( ["training_log[duration_m]", minutes] );
    if (comment.length > 0)
        parameters.push( ["training_log[comment]", comment] );
    parameters.push( ["training_log[mood]", mood] );
    if (distance.length > 0) {
        parameters.push( ["training_log[sport_params][0][name]", "distance"] );
        parameters.push( ["training_log[sport_params][0][value]", distance] );
    }

    log("params: " + parameters);

    var req = getAPIOAuthRequest("POST", API_URL_POST_ENTRY, null, [appItem.accessToken, appItem.accessTokenSecret], parameters, null, REQUEST_TYPE_POST_ENTRY);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send();

}

function readyStateHandler(request, requestType) {
    if(request && request.readyState === 4) {
        log("Status: " + request.status);
        if  (request.status === 200) {
            if (requestType === REQUEST_TYPE_GET_SPORTS) {
                log("GET SPORTS REQUEST");
                handleGetSportsResponse(request.responseText);
                // no note here
            } else if (requestType === REQUEST_TYPE_POST_ENTRY) {
                log("POST ENTRY RESPONSE");
                mainView.infoVisible = true;
                mainView.infoText = qsTr("Posted succesfully");
            } else {
                log("Unknown request type");
                mainView.errorVisible = true;
                mainView.errorText = qsTr("Unknown request");
            }
        } else if (request.status === 401) {
            log(request.statusText);
            log("UNAUTHORIZED");
            log(request.responseText);
            appItem.authenticated = false;
            //clearCredentials();
            mainView.errorVisible = true;
            mainView.errorText = qsTr("Unauthorized!");
        } else {
            log("HTTP Status: " + request.status);
            log(request.responseText);
//            mainView.errorVisible = true;
//            mainView.errorText = qsTr("Unknown error");
        }
    }
}

function handleGetSportsResponse(responseText) {
    log("handleGetSportsResponse");

    // Hack. Do properly when  time
    responseText = responseText.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
    responseText = responseText.replace("<sports>", "");
    responseText = responseText.replace("</sports>", "");

    // Store all <sport> elements
    sportsXML = sportsXML.concat(responseText);

    sportsPage = sportsPage + 1;
    if (sportsPage <= TOTAL_SPORTS_PAGE_COUNT) {
        getSports(sportsPage);
    } else {
        appItem.loadingSports = false;
        // Received all pages. Recreate the whole <sports>-element
        sportsXML = "<sports>" + sportsXML + "</sports>";
        sportsModel.xml = sportsXML;
        log(sportsXML);
    }

}

function getValidator(resource, password)
{
    return b64_sha1(resource + password) + "=";
}

function getDigest(validator, timestamp, nonce)
{
    return b64_sha1(nonce + timestamp + validator) + "=";
}

function getTimestamp()
{
    return parseInt((new Date).valueOf() / 1000);
}

function getNonce()
{
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var result = "";
    for (var i = 0; i < 9; ++i) {
        var rnum = Math.floor(Math.random() * chars.length);
        result += chars.substring(rnum, rnum+1);
    }
    return result;
}

// Helper function to create xhrs
function getAPIOAuthRequest(type, url, authParameters, credentials, parameters, body, requestType) {
    var timestamp =  getTimestamp();
    var nonce = getNonce();

    var parameterlist = new Array();
    parameterlist.push( ["oauth_consumer_key", consumerKey] );
    parameterlist.push( ["oauth_nonce", nonce] );
    parameterlist.push( ["oauth_timestamp", timestamp] );
    parameterlist.push( ["oauth_signature_method", "HMAC-SHA1"] );
    parameterlist.push( ["oauth_version", "1.0"] );
    if (credentials)
        parameterlist.push( ["oauth_token", credentials[0]] );

//    if (authParameters)
//        parameterlist = parameterlist.concat(authParameters);

    if (parameters)
        parameterlist = parameterlist.concat(parameters);

    parameterlist.sort(function(a,b) {
                           if (a[0] < b[0]) return  -1;
                           if (a[0] > b[0]) return 1;
                           if (a[1] < b[1]) return -1;
                           if (a[1] > b[1]) return 1;
                           return 0;
                       });

    var normalized = "";
    if (body)
        normalized = body + "&";
    for (var ii = 0; ii < parameterlist.length; ++ii) {
        if (ii != 0) normalized += "&";
        normalized += parameterlist[ii][0] + "=" + encodeURIComponent(parameterlist[ii][1]);
    }

    normalized = normalized.replace(/\[/g, "%5B");
    normalized = normalized.replace(/\]/g, "%5D");

    var basestring = type + "&" + encodeURIComponent(url) + "&" + encodeURIComponent(normalized);

    var keystring = encodeURIComponent(consumerSecret) + "&";
    if (credentials)
        keystring += encodeURIComponent(credentials[1]);

    var signature = b64_hmac_sha1(keystring, basestring);

    var authHeader = "OAuth ";
    authHeader += "oauth_consumer_key=\"" + encodeURIComponent(consumerKey) + "\"";
    authHeader += ", oauth_nonce=\"" + encodeURIComponent(nonce) + "\"";
    authHeader += ", oauth_timestamp=\"" + encodeURIComponent(timestamp) + "\"";
    authHeader += ", oauth_signature=\"" + encodeURIComponent(signature) + "\"";
    authHeader += ", oauth_signature_method=\"HMAC-SHA1\"";
    authHeader += ", oauth_version=\"1.0\"";
    if(authParameters)
        for (var ii = 0; ii < authParameters.length; ii++)
            authHeader += ", " + authParameters[ii][0] + "=\"" + encodeURIComponent(authParameters[ii][1]) + "\"";

    if (credentials)
        authHeader += ", oauth_token=\"" + encodeURIComponent(credentials[0]) + "\"";


    var requrl = url;
    if (parameters) {
        for (var ii = 0; ii < parameters.length; ++ii) {
            if (ii == 0) requrl += "?";
            else requrl += "&";

            requrl += parameters[ii][0] + "=" + encodeURI(parameters[ii][1]);
        }
    }

    var xhr = new XMLHttpRequest;
    xhr.open(type, requrl);
    xhr.setRequestHeader("Authorization", authHeader);
    xhr.setRequestHeader("Accept-Language", "en");
    xhr.setRequestHeader("User-Agent", "FutuHeia/0.1.1");
    xhr.onreadystatechange = function() { readyStateHandler(xhr, requestType); }

    return xhr;
}

